import React, { useState, useEffect } from 'react';
import { Tabs, Card, Button, Input, Space, Typography, message, Modal, Tag } from 'antd';
import { CopyOutlined, KeyOutlined, AppstoreOutlined, PlusOutlined, DeleteOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { useAuth } from '../../context/AuthContext';
import api from '../../utils/api';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

// 模拟API密钥数据
const mockApiKeys = [
  {
    id: 1,
    name: '默认密钥',
    key: 'sk_test_123456789abcdef',
    created_at: '2024-03-20 10:00:00',
    last_used: '2024-03-21 15:30:00'
  }
];

// 模拟我的插件数据
const mockMyPlugins = [
  {
    id: 1,
    name: '智能翻译助手',
    desc: '支持多语言实时翻译，适用于跨境沟通。',
    url: 'https://plugin.example.com/translate',
    tags: ['NLP', '翻译', 'AI'],
    status: 'active'
  }
];

interface ApiKey {
  id: number;
  name: string;
  key: string;
  created_at: string;
  last_used: string;
}

interface Plugin {
  id: number;
  name: string;
  desc: string;
  url: string;
  tags: string[];
  status: string;
}

// 格式化密钥显示
const formatApiKey = (key: string, showFull: boolean = false) => {
  if (showFull) return key;
  if (key.length <= 8) return key;
  return `${key.slice(0, 4)}${'*'.repeat(key.length - 8)}${key.slice(-4)}`;
};

const UserCenter: React.FC = () => {
  const { user } = useAuth();
  const [apiKeys, setApiKeys] = useState<ApiKey[]>(mockApiKeys);
  const [myPlugins, setMyPlugins] = useState<Plugin[]>(mockMyPlugins);
  const [newKeyName, setNewKeyName] = useState('');
  const [isCreateKeyModalVisible, setIsCreateKeyModalVisible] = useState(false);
  const [visibleKeys, setVisibleKeys] = useState<{ [key: number]: boolean }>({});

  // 切换密钥显示状态
  const toggleKeyVisibility = (id: number) => {
    setVisibleKeys(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  // 创建新密钥
  const handleCreateKey = () => {
    if (!newKeyName.trim()) {
      message.error('请输入密钥名称');
      return;
    }
    // TODO: 调用后端API创建密钥
    const newKey: ApiKey = {
      id: apiKeys.length + 1,
      name: newKeyName,
      key: `sk_test_${Math.random().toString(36).substr(2, 15)}`,
      created_at: new Date().toLocaleString(),
      last_used: '-'
    };
    setApiKeys([...apiKeys, newKey]);
    setNewKeyName('');
    setIsCreateKeyModalVisible(false);
    message.success('创建密钥成功');
  };

  // 删除密钥
  const handleDeleteKey = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '删除后该密钥将无法使用，是否继续？',
      onOk: () => {
        // TODO: 调用后端API删除密钥
        setApiKeys(apiKeys.filter(key => key.id !== id));
        message.success('删除密钥成功');
      }
    });
  };

  // 复制密钥
  const handleCopyKey = (key: string) => {
    try {
      // 尝试使用现代 Clipboard API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(key).then(() => {
          message.success('复制成功');
        }).catch(() => {
          fallbackCopy(key);
        });
      } else {
        fallbackCopy(key);
      }
    } catch (err) {
      fallbackCopy(key);
    }
  };

  // 备选复制方案
  const fallbackCopy = (text: string) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        message.success('复制成功');
      } else {
        message.error('复制失败');
      }
    } catch (err) {
      message.error('复制失败');
    }

    document.body.removeChild(textArea);
  };

  return (
    <div className="hide-scrollbar" style={{ padding: 24, maxHeight: 'calc(100vh - 120px)', overflowY: 'auto', overflowX: 'hidden' }}>
      <Tabs defaultActiveKey="keys">
        <TabPane 
          tab={
            <span>
              <KeyOutlined />
              我的密钥
            </span>
          } 
          key="keys"
        >
          <div style={{ marginBottom: 16 }}>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => setIsCreateKeyModalVisible(true)}
            >
              创建新密钥
            </Button>
          </div>
          
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            {apiKeys.map(key => (
              <Card 
                key={key.id}
                title={
                  <Space>
                    <Text strong>{key.name}</Text>
                    <Tag color="blue">API密钥</Tag>
                  </Space>
                }
                extra={
                  <Space>
                    <Button 
                      type="text" 
                      icon={visibleKeys[key.id] ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                      onClick={() => toggleKeyVisibility(key.id)}
                    >
                      {visibleKeys[key.id] ? '隐藏' : '显示'}
                    </Button>
                    <Button 
                      type="text" 
                      icon={<CopyOutlined />}
                      onClick={() => handleCopyKey(key.key)}
                    >
                      复制
                    </Button>
                    <Button 
                      type="text" 
                      danger 
                      icon={<DeleteOutlined />}
                      onClick={() => handleDeleteKey(key.id)}
                    >
                      删除
                    </Button>
                  </Space>
                }
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div>
                    <Text type="secondary">密钥：</Text>
                    <Text>{formatApiKey(key.key, visibleKeys[key.id])}</Text>
                  </div>
                  <div>
                    <Text type="secondary">创建时间：</Text>
                    <Text>{key.created_at}</Text>
                  </div>
                  <div>
                    <Text type="secondary">最后使用：</Text>
                    <Text>{key.last_used}</Text>
                  </div>
                </Space>
              </Card>
            ))}
          </Space>
        </TabPane>

        <TabPane 
          tab={
            <span>
              <AppstoreOutlined />
              我的插件
            </span>
          } 
          key="plugins"
        >
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            {myPlugins.map(plugin => (
              <Card 
                key={plugin.id}
                title={
                  <Space>
                    <Text strong>{plugin.name}</Text>
                    <Tag color="green">已激活</Tag>
                  </Space>
                }
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Paragraph>{plugin.desc}</Paragraph>
                  <div>
                    <Text type="secondary">接入URL：</Text>
                    <Text copyable>{plugin.url}</Text>
                  </div>
                  <div>
                    <Text type="secondary">标签：</Text>
                    {plugin.tags.map(tag => (
                      <Tag key={tag} color="blue">{tag}</Tag>
                    ))}
                  </div>
                </Space>
              </Card>
            ))}
          </Space>
        </TabPane>
      </Tabs>

      {/* 创建密钥弹窗 */}
      <Modal
        title="创建新密钥"
        open={isCreateKeyModalVisible}
        onOk={handleCreateKey}
        onCancel={() => {
          setIsCreateKeyModalVisible(false);
          setNewKeyName('');
        }}
      >
        <Input
          placeholder="请输入密钥名称"
          value={newKeyName}
          onChange={e => setNewKeyName(e.target.value)}
        />
      </Modal>
    </div>
  );
};

export default UserCenter; 